import React, { useState, useEffect } from 'react'
import { useParams } from "react-router-dom"
import {
  Form,
  Input,
  Button,
  Divider,
  Select,
  DatePicker,
  Affix,
  Space,
  Row,
  Col,
  Table,
  Drawer,
  Popconfirm,
  notification
} from 'antd'
import { Form as SalesForm } from 'antd'
import { Form as CommunityForm } from 'antd'
import { Form as TypeForm } from 'antd'
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined } from '@ant-design/icons'
import styles from './index.less'
import Tags from './components/Tags'
import UploadImage from './components/UploadImage'
import { PicturesWall as UploadImageType } from './components/UploadImage'
import HouseTypeColumns from './HouseTypeColumns'
import AddressColumnns from './AddressColumnns'
import {
  getEstate,
  createHouseType,
  updateHouseType,
  delHouseType,
  createTag,
  delTag,
  getTags,
  getImg,
  updateEstate,
  delEstate,
  getAddressList,
  delImg
} from '@/services/ant-design-pro/api';
import _ from 'lodash';
import moment from 'moment'
import { history } from 'umi';



type FormInterFace = Record<string, any>;

// type LayoutType = Parameters<typeof Form>[0]['layout']
const { Option } = Select
const { Item } = Form

export default function (): React.ReactNode {
  /**
   * form data
   */
  const [form] = Form.useForm()
  const [salesForm] = SalesForm.useForm()
  const [communityForm] = CommunityForm.useForm()
  const [typeForm] = TypeForm.useForm()
  /**
   * state
   */
  const [isDrawerVisible, setIsDrawerVisible] = useState(false)
  const [isAddressVisible, setAddressVisible] = useState(false)
  const [addressValue, setAddressValue] = useState('')
  const [estateDetail, setEstateDetail] = useState({})
  const { id } = useParams();
  const [houseTypeAction, setHouseTypeAction] = useState('create')
  const [estateTags, setEstateTags] = useState([])
  const [houseTpyeId, setHouseTypeId] = useState('')
  const [estateImage, setEstateImage] = useState([])
  const [houseTypeImage, setHouseTypeImage] = useState([])
  const [adData, setAdData] = useState<API.AddressData[] | []>([])
  const [adTableLoading, setAdTableLoading] = useState(false)
  /**
 * 获取楼盘信息
 */
  const queryEstate = async (estateId: number) => {
    try {
      const resp = await getEstate({ id: estateId });

      const estate: FormInterFace = _.get(resp, 'data', {});
      setEstateDetail(estate)

      form.setFieldsValue(estate)
      communityForm.setFieldsValue(estate)
      /**
       * 回填前需要将最近开盘时间, 最近交房时间转换成 moment 对象
       */
      estate.last_opening_time = estate.last_opening_time ? moment(estate.last_opening_time) : ''
      estate.last_delivery_time = estate.last_delivery_time ? moment(estate.last_delivery_time) : ''
      salesForm.setFieldsValue(estate)
    } catch (err) {
      throw new Error(err)
    }
  }


  /**
   * function
   */
  function onDrawerClose() {
    setIsDrawerVisible(false)
  }
  // function onDrawerOpen() {
  //   setIsDrawerVisible(true)
  // }

  async function onSave() {
    const formValue = form.getFieldsValue()
    const communityFormValue = communityForm.getFieldsValue()
    let salesFormValue = salesForm.getFieldsValue()

    const openingTime = salesForm.getFieldValue('last_opening_time')
      && salesForm.getFieldValue('last_opening_time').format('YYYY-MM-DD') // last_opening_time
    const deliveryTime = salesForm.getFieldValue('last_delivery_time')
      && salesForm.getFieldValue('last_delivery_time').format('YYYY-MM-DD')// last_delivery_time

    salesFormValue = { ...salesFormValue, last_opening_time: openingTime, last_delivery_time: deliveryTime }

    const params = { ...formValue, ...communityFormValue, ...salesFormValue }
    await updateEstate({ id, data: params }).then((res) => {
      if (res.status === 200) {
        notification.success({ message: '保存成功:' })
      } else {
        notification.error({ message: res.message || '保存失败:' })
      }
    }).catch(() => notification.error({ message: '保存失败:' }))
  }

  /**
   * 编辑户型(打开Drawer并回填数据)
   * @param record 
   */
  const handleEditHouse = (record: any) => {
    setHouseTypeImage([])
    setIsDrawerVisible(true)
    setHouseTypeAction('edit')
    const id = _.get(record, 'id')
    setHouseTypeId(id)
    const houseTpyeList = _.get(estateDetail, 'house_type_list', [])
    const houseType = houseTpyeList.filter(val => val.id === id)[0]
    typeForm.setFieldsValue(houseType)

  }

  /**
   * 保存户型
   */
  const handleSaveHouseType = async () => {
    const result = typeForm.getFieldValue()
    // result.area = +result.area
    // result.room_count = +result.room_count
    // result.total_price = +result.total_price
    if (houseTypeAction === 'edit') {
      await updateHouseType({ id: result.id, data: { ...result, estate_id: +id } })
    } else {
      await createHouseType({ data: { ...result, estate_id: +id } })
    }
    await queryEstate(id)
    setIsDrawerVisible(false)
  }

  /**
   * 新增户型
   */
  const handleCreatHouseType = () => {
    // 修改状态
    setHouseTypeAction('create')
    // 打开抽屉
    setIsDrawerVisible(true)
    // 重置表单
    typeForm.resetFields();
    setHouseTypeImage([]);

  }

  /**
   * 删除户型
   */
  const handleDelHouse = async (record) => {
    const { id: houseTypeId } = record;
    await delHouseType({ id: houseTypeId })
    await queryEstate(id) // 此id为estateId
  }
  const handleDelHouseType = () => {
    const result = typeForm.getFieldValue();
    handleDelHouse(result)
    // 关闭抽屉
    setIsDrawerVisible(false)
  }

  /**
   * 获取tags
   */
  const queryTags = async (estateId) => {
    const resp = await getTags({ id: estateId })
    const tags = _.get(resp, 'data', [])
    setEstateTags(tags)
    // 获取tags后,保存一次state
    // setEstateDetail({...estateDetail, tag_list: tags})
  }

  /**
   * 删除tags
   */
  const deleteTag = async (tagId, estateId) => {
    await delTag({ id: tagId })
    await queryTags(estateId)
  }

  /**
   * 创建tag
   */
  const newTag = async (estateId, tagName) => {
    const params = { estate_id: estateId, tag_name: tagName }
    await createTag({ data: params })
    await queryTags(estateId)
  }

  /**
   * 获取图片
   */
  const queryImg = async () => {
    const params = {
      bind_id: isDrawerVisible ? +houseTpyeId : +id,
      bind_type: isDrawerVisible ? 1 : 0,
    }
    const resp = await getImg({ params })
    const { data: image } = resp;

    if (isDrawerVisible) {
      if (houseTypeAction === 'edit') {
        setHouseTypeImage(image)
      }
    } else {
      setEstateImage(image)
    }
  }

  /**
   * 删除楼盘
   */
  const handleDelEstate = async () => {
    await delEstate({ id }).then(() => history.push('/base-data/community-list/')).catch(err => { throw err })
  }


  /**
   * 地址列表相关
   */
  async function handleAdList(value: string) {
    const params = {
      boundary: 'region(广州,0)',
      page_size: 20,
      page_index: 1,
      keyword: value,
      orderby: "_distance"
    }
    setAdTableLoading(true)
    const res = await getAddressList({ params })
    setAdTableLoading(false)
    setAdData(res.data)
  }

  async function openAddress(value: string) {
    setAddressValue(value)
    setAddressVisible(true)
    await handleAdList(value)
  }

  async function handleAddressListSearch(value: string) {
    await handleAdList(value)
  }

  /**
   * 关闭地址列表
   */
  function closeAddress() {
    setAddressVisible(false)
  }

  function handleChooseAd(record: API.AddressData) {
    console.log(record)
    const data = {
      address: record.address,
      lng: record.location.lng,
      lat: record.location.lat,
      district: record.ad_info.district
    }
    form.setFieldsValue(data)
    setAddressVisible(false)
  }

  /**
   * effect
   */
  useEffect(() => {
    queryTags(id)
    queryEstate(id)
    queryImg()
  }, [])

  /**
   * 其他
   */
  const cols = [
    ...HouseTypeColumns,
    {
      title: '编辑',
      render: (tetx: string, record: unknown) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleEditHouse(record)}> 编辑</Button>
            <Popconfirm
              title="确认删除?"
              onConfirm={() => handleDelHouse(record)}
              okText="确认"
              cancelText="取消"
            >
              <Button type="link" danger >删除</Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  function onImageRemove(file: any) {
    console.log(file)
    // return Promise.reject(false)
    return new Promise((resolve, reject) => {
      delImg({ id: file.id })
        .then((res) => {
          if (res.status === 200) {
            resolve(res)
          } else {
            notification.error({ message: '删除失败' })
            reject(false)
          }
        })
        .catch(() => {
          notification.error({ message: '网络不通畅' })
          reject(false)
        })
    })
  }
  const adColumns = [
    ...AddressColumnns,
    {
      title: '编辑',
      render: (text: string, record: API.AddressData) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleChooseAd(record)}>选择</Button>
          </Space>
        )

      }
    }
  ]

  return (
    <>
      <PageContainer>
        <h2>楼盘编辑</h2>
        <div className={styles.detail_content}>
          <Form layout="inline" form={form}>

            <Item label="楼盘名称" className={styles.item_box} required name="estate_name">
              <Input.Search
                enterButton="获取详细地址"
                placeholder="请输入"
                style={{ width: '300px' }}
                onSearch={openAddress}
              />
            </Item>
            <Item label="参考总价" className={styles.item_box} name="total_price">
              <Input placeholder="请输入" suffix="万元" type="number" />
            </Item>
            <Item label="参考均价" className={styles.item_box} name="average_price">
              <Input placeholder="请输入" type="number" suffix="元" />
            </Item>
            <Item label="产权年限" className={styles.item_box} name="age_limit">
              <Input placeholder="请输入" type="number" suffix="年" />
            </Item>
            <Item label="开发商" className={styles.item_box} name="developer_name">
              <Input placeholder="请输入" />
            </Item>
            <Item label="建筑类型" className={styles.item_box} name="building_type">
              <Input placeholder="请输入" />
            </Item>
            <Item label="物业类型" className={styles.item_box} name="property_type">
              <Select style={{ width: 170 }}>
                <Option value="住宅">住宅</Option>
                <Option value="商业">商业</Option>
                <Option value="公寓">公寓</Option>
              </Select>
            </Item>
            <Item label="装修类型" className={styles.item_box} name="decoration_type">
              <Select style={{ width: 170 }}>
                <Option value="毛坯">毛坯</Option>
                <Option value="精装修">精装</Option>
              </Select>
            </Item>
            <Item
              label="地铁站"
              className={styles.item_box}
              name="subway_station"
            >
              <Input placeholder="请输入" />
            </Item>
            <Item
              label="详细地址"
              style={{ width: '500px' }}
              className={styles.item_box}
              name="address">
              <Input disabled />
            </Item>
            <Item label="经度(longitude)" className={styles.item_box} name="lng">
              <Input disabled />
            </Item>
            <Item label="维度(latitude)" className={styles.item_box} name="lat">
              <Input disabled />
            </Item>
            <Item label="区域" className={styles.item_box} name="district">
              <Input disabled />
            </Item>
          </Form>
        </div>

        <h2>销售消息</h2>
        <div className={styles.detail_content}>
          <SalesForm layout="inline" form={salesForm}>
            <Item label="销售状态" className={styles.item_box} name="is_sales">
              <Select style={{ width: 170 }}>
                <Option value={0}>停售</Option>
                <Option value={1}>在售</Option>
                <Option value={2}>未开盘</Option>
                <Option value={3}>收筹中</Option>
              </Select>
            </Item>
            <Item label="销售楼栋" className={styles.item_box} name="planning_building">
              <Input placeholder="请输入" />
            </Item>
            <Item label="最新开盘时间" className={styles.item_box} name="last_opening_time">
              <DatePicker format="YYYY-MM-DD" />
            </Item>
            <Item label="最近交房时间" className={styles.item_box} name="last_delivery_time">
              <DatePicker format="YYYY-MM-DD" />
            </Item>
            <Item label="售楼地址" className={styles.item_box} name="sales_address">
              <Input placeholder="请输入" style={{ width: 300 }} />
            </Item>
          </SalesForm>
        </div>

        <h2>小区概况</h2>
        <div className={styles.detail_content}>
          <CommunityForm layout="inline" form={communityForm}>
            <Item label="占地面积" className={styles.item_box} name="total_area">
              <Input placeholder="请输入" type="number" suffix="㎡" />
            </Item>
            <Item label="建筑面积" className={styles.item_box} name="building_area">
              <Input placeholder="请输入" type="number" suffix="㎡" />
            </Item>
            <Item label="容积率" className={styles.item_box} name="floor_area_ratio">
              <Input placeholder="请输入" type="number" suffix="%" />
            </Item>
            <Item label="绿化率" className={styles.item_box} name="greening_rate">
              <Input placeholder="请输入" type="number" suffix="%" />
            </Item>
            <Item label="规划车位" className={styles.item_box} name="planning_parking">
              <Input placeholder="请输入" />
            </Item>
            <Item label="车位配比" className={styles.item_box} name="parking_space_ratio">
              <Input placeholder="请输入" />
            </Item>
            <Item label="规划楼栋" className={styles.item_box} name="planning_building">
              <Input placeholder="请输入" />
            </Item>
            <Item label="规划户型" className={styles.item_box} name="planning_house_type">
              <Input placeholder="请输入" />
            </Item>
            <Item label="物业公司" className={styles.item_box} name="property_name">
              <Input placeholder="请输入" />
            </Item>
            <Item label="物业费用" className={styles.item_box} name="property_expenses">
              <Input placeholder="请输入" type="number" suffix="元/平方米/月" />
            </Item>
            <Item label="供水" className={styles.item_box} name="water_supply">
              <Input placeholder="请输入" />
            </Item>
            <Item label="供电" className={styles.item_box} name="electricity_supply">
              <Input placeholder="请输入" />
            </Item>
          </CommunityForm>
        </div>
        <h2>楼盘卖点</h2>
        <div className={styles.detail_content}>
          <SalesForm form={salesForm} labelCol={{ span: 3 }} labelAlign="right">
            <Item name="traffic" label="交通">
              <Input.TextArea
                placeholder="请输入"
                autoSize={{ minRows: 3, maxRows: 5 }} />
            </Item>
            <Item name="community_supporting" label="小区配套">
              <Input.TextArea
                placeholder="请输入"
                autoSize={{ minRows: 3, maxRows: 5 }} />
            </Item>
            <Item name="other" label="其他">
              <Input.TextArea
                placeholder="请输入"
                autoSize={{ minRows: 3, maxRows: 5 }} />
            </Item>
          </SalesForm>
        </div>
        <h2>其他信息</h2>
        <div className={styles.detail_content}>
          <p>标签</p>
          <Tags tags={estateTags} deleteTag={deleteTag} newTag={newTag} estateId={id} />
          <Divider />

          <p>上传banner图</p>
          <UploadImage fileList={estateImage} bindType="estate" bindId={id} onRemove={onImageRemove} />
          <Divider />

          <p>排序</p>
          <SalesForm form={salesForm}>
            <Item name="order">
              <Input placeholder="请输入" style={{ width: 450 }} type="number" />
            </Item>
          </SalesForm>

          <p>备注</p>
          <SalesForm form={salesForm}>
            <Item name="remark">
              <Input placeholder="请输入" style={{ width: 450 }} />
            </Item>
          </SalesForm>
        </div>

        <h2>房型信息</h2>
        <div className={styles.detail_content}>
          <p>
            <Button icon={<PlusOutlined />} onClick={handleCreatHouseType}>添加房型</Button>
          </p>
          <div>
            <Table
              columns={cols}
              dataSource={_.get(estateDetail, 'house_type_list', [])} rowKey="id" pagination={false}></Table>
          </div>
        </div>
      </PageContainer>
      {/* 获取详细地址抽屉 */}
      <Drawer
        title="获取详细地址"
        width={800}
        visible={isAddressVisible}
        onClose={closeAddress}
      >
        <Input.Search
          value={addressValue}
          onChange={(v) => setAddressValue(v.target.value)}
          onSearch={handleAddressListSearch}
          enterButton
        />

        <div>
          <Table
            columns={adColumns}
            dataSource={adData}
            loading={adTableLoading}
            rowKey="id"
          />
        </div>
      </Drawer>

      {/* 户型编辑抽屉 */}
      <Drawer
        title="户型编辑"
        width={500}
        onClose={onDrawerClose}
        visible={isDrawerVisible}
        bodyStyle={{ paddingBottom: 80 }}
        afterVisibleChange={queryImg}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            {
              houseTypeAction === 'edit' && (
                <Popconfirm
                  title="确认删除?"
                  onConfirm={handleDelHouseType}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button style={{ marginRight: 8 }}>
                    删除
                  </Button>
                </Popconfirm>

              )
            }
            <Button onClick={handleSaveHouseType} type="primary">
              保存
            </Button>
          </div>
        }
      >
        <TypeForm form={typeForm} >
          <Row gutter={16}>
            <Col span={12}>
              <Item
                label="格局"
                name="pattern"
              >
                <Input placeholder="请输入" />
              </Item>
            </Col>
            <Col span={12}>
              <Item
                label="建面"
                name="area"
              >
                <Input placeholder="请输入" type="number" suffix="㎡" />
              </Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Item
                label="朝向"
                name="towards"
              >
                <Input placeholder="请输入" />
              </Item>
            </Col>
            <Col span={12}>
              <Item
                label="总价"
                name="total_price"
              >
                <Input placeholder="请输入" type="number" suffix="万元" />

              </Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Item
                label="房间数"
                name="room_count"
              >
                <Input placeholder="请输入" type="number" suffix="间" />

              </Item>
            </Col>
            <Col span={12}>
              <Item
                label="是否在售"
                name="in_store"
              >
                <Select>
                  <Option value={0}>停售</Option>
                  <Option value={1}>在售</Option>
                </Select>
              </Item>
            </Col>
          </Row>
        </TypeForm>

        <p>上传户型图</p>
        {
          isDrawerVisible ? (
            <UploadImageType
              fileList={houseTypeImage}
              bindType="houseType"
              bindId={houseTpyeId}
              onRemove={onImageRemove} />
          ) : null
        }
      </Drawer>

      <Affix offsetBottom={0}>
        <div style={{ display: 'flex', justifyContent: "flex-end", padding: "20px", background: 'rgba(255,255,255, .75)', }} >
          <Space>
            {/* <Button>预览</Button> */}
            <Popconfirm
              title={`确认删除?`}
              onConfirm={handleDelEstate}
              okText="确认"
              cancelText="取消"
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
            <Button type="primary" onClick={onSave}>保存</Button>
          </Space>
        </div>
      </Affix>
    </>
  )
}